package com.zby.admin.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zby.admin.mapper.AdminMapper;
import com.zby.admin.mapper.UserMapper;
import com.zby.admin.pojo.Admin;
import com.zby.admin.pojo.LoginResult;
import com.zby.admin.pojo.User;
import com.zby.admin.pojo.dto.AdminDto;
import com.zby.admin.pojo.dto.UserDto;
import com.zby.admin.pojo.vo.UserVo;
import com.zby.admin.service.UserService;
import com.zby.utils.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserServiceImp extends ServiceImpl<AdminMapper, Admin> implements UserService {
    
    @Resource
    private UserMapper userMapper;
    
    @Override
    public LoginResult login(AdminDto adminDto, HttpServletRequest request) {
        if (adminDto.getUsername()== null||adminDto.getPassword()== null){
            throw new RuntimeException("用户名或密码不能为空");
        }
        if(adminDto.getUsername().length()<4){
            throw new RuntimeException("用户名长度不能小于4");
        }
        if(adminDto.getPassword().length()<6){
            throw new RuntimeException("密码长度不能小于6");
        }
        
        // 先查询管理员表
        Admin admin = new Admin();
        admin.setAdminName(adminDto.getUsername());
        admin.setAdminPassword(adminDto.getPassword());

        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.eq("admin_name", admin.getAdminName()).eq("admin_password", admin.getAdminPassword());
        Admin adminResult = this.getOne(adminQueryWrapper);
        
        // 如果管理员存在
        if (adminResult != null) {
            HttpSession session = request.getSession();
            session.setAttribute("adminNickName", adminResult.getAdminNickname());
            session.setAttribute("adminId", adminResult.getId());
            Object attribute = request.getSession().getAttribute("adminNickName");
            System.out.println(attribute);
            
            LoginResult loginResult = new LoginResult();
            loginResult.setAdmin(adminResult);
            loginResult.setDetermineRole(true);


            return loginResult;
        }
        
        // 管理员不存在，查询用户表
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_name", adminDto.getUsername()).eq("user_password", adminDto.getPassword());
        User userResult = userMapper.selectOne(userQueryWrapper);
        
        // 如果用户存在
        if (userResult != null) {
            HttpSession session = request.getSession();
            session.setAttribute("userNickName", userResult.getUserNickname());
            session.setAttribute("userId", userResult.getId());
            
            LoginResult loginResult = new LoginResult();
            loginResult.setUser(userResult);
            loginResult.setDetermineRole(false);

            return loginResult;
        }
        
        // 用户和管理员都不存在
        return null;
    }

    @Override
    public Page<Admin> selectPage(Integer page, Integer pageSize) {
        Page<Admin> page1 = new Page<>(page, pageSize);
        return this.page(page1);
    }

    @Override
    public boolean insertSave(AdminDto adminDto, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        Object attribute = session.getAttribute("adminNickName");
        // 先判断 attribute 是否为 null
        if (attribute == null) {
            // 可选：记录日志或抛出自定义异常
            System.out.println("用户未登录或会话已过期");
            return false;
        }
        // 查询用户名是否重复(待做)

        String adminNickName = attribute.toString();
        System.out.println(adminNickName);
        if (adminNickName.equals("管理员")){
            Admin admin = new Admin();
            admin.setAdminName(adminDto.getUsername());
            admin.setAdminPassword("123456");
            admin.setAdminNickname(adminDto.getNickname());
            return this.save(admin);

        }
        return false;
    }

    @Override
    public boolean updateAdminInfo(AdminDto adminDto, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        Object sessionAttribute = session.getAttribute("adminNickName");
        Object sessionId = session.getAttribute("adminId");

        // 先判断 attribute 是否为 null
        if (sessionAttribute == null||sessionId == null) {
            System.out.println("用户未登录或会话已过期");
        }
        // 判断 id 是否为 null
        if (adminDto.getId() == null){
            throw new RuntimeException("用户不存在");
        }
        // 昵称长度不能小于4
        if (adminDto.getUsername().length() < 4){
            throw new RuntimeException("昵称长度不能小于4");
        }
        // 判断是否为管理员
        String adminNickName = sessionAttribute.toString();
        long requestId = Long.parseLong(sessionId.toString());
        if(adminNickName.equals("商家用户")){
            if(requestId != adminDto.getId()){
                throw new RuntimeException("权限不足");
            }
        }
        Admin admin = new Admin();
        admin.setId(adminDto.getId());
        admin.setAdminNickname(adminDto.getNickname());
        admin.setAdminName(adminDto.getUsername());
        admin.setAdminProfilePictureSrc(adminDto.getAvatarUrl());
        UpdateWrapper<Admin> objectUpdateWrapper = new UpdateWrapper<>();
        UpdateWrapper<Admin> adminUpdateWrapper = objectUpdateWrapper
                .eq("id", admin.getId())
                .set("admin_name", admin.getAdminName())
                .set("admin_nickname", admin.getAdminNickname())
                .set("admin_profile_picture_src", admin.getAdminProfilePictureSrc());
        boolean update = this.update(admin, adminUpdateWrapper);
        if (!update) {
            throw new RuntimeException("修改用户信息失败");

        }
        return true;
    }


    @Override
    public boolean insertData(UserDto userVo) {
        // 检查用户名是否已存在
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_name", userVo.getUserName());
        User existingUser = userMapper.selectOne(userQueryWrapper);
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建新用户对象
        User user = new User();
        user.setUserName(userVo.getUserName());
        user.setUserNickname(userVo.getUserNickname());
        // 注意：UserVo中没有密码字段，这里设置默认密码
        user.setUserPassword("123456");
        user.setUserRealname(userVo.getUserRealname());
        user.setUserGender(userVo.getUserGender());
        user.setUserBirthday(userVo.getUserBirthday());


        // 保存用户信息
        int result = userMapper.insert(user);
        return result > 0;
    }
    
    @Override
    public Page<UserVo> selectUserPage(Integer page, Integer pageSize) {
        // 创建分页对象
        Page<User> userPage = new Page<>(page, pageSize);
        
        // 查询用户数据
        Page<User> resultPage = userMapper.selectPage(userPage, new QueryWrapper<User>().eq("deleted", 0));
        
        // 转换为UserVo分页对象
        Page<UserVo> userVoPage = new Page<>();
        userVoPage.setCurrent(resultPage.getCurrent());
        userVoPage.setSize(resultPage.getSize());
        userVoPage.setTotal(resultPage.getTotal());
        
        // 转换用户对象为UserVo对象
        userVoPage.setRecords(resultPage.getRecords().stream().map(user -> {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            return userVo;
        }).toList());
        
        return userVoPage;
    }
    
    @Override
    public UserVo getUserInfo(HttpServletRequest request) {
        // 从会话中获取用户ID
        HttpSession session = request.getSession(false);
        if (session == null) {
            return null;
        }
        
        Object userIdObj = session.getAttribute("userId");
        if (userIdObj == null) {
            return null;
        }
        
        try {
            Long userId = Long.valueOf(userIdObj.toString());
            User user = userMapper.selectById(userId);
            if (user == null) {
                return null;
            }
            
            UserVo userVo = new UserVo();
            userVo.setId(user.getId());
            userVo.setUserName(user.getUserName());
            userVo.setUserNickname(user.getUserNickname());
            userVo.setUserRealname(user.getUserRealname());
            userVo.setUserGender(user.getUserGender());
            userVo.setUserBirthday(user.getUserBirthday());
            userVo.setUserProfilePictureSrc(user.getUserProfilePictureSrc());
            userVo.setCreateTime(user.getCreateTime());
            userVo.setUpdateTime(user.getUpdateTime());
            
            return userVo;
        } catch (NumberFormatException e) {
            return null;
        }
    }
    
    @Override
    public boolean updateUserInfo(UserDto userDto, HttpServletRequest request) {
        // 从会话中获取用户ID
        HttpSession session = request.getSession(false);
        if (session == null) {
            return false;
        }
        
        Object userIdObj = session.getAttribute("userId");
        if (userIdObj == null) {
            return false;
        }
        
        try {
            Long userId = Long.valueOf(userIdObj.toString());
            User user = userMapper.selectById(userId);
            if (user == null) {
                    return false;
            }
            if(!Objects.equals(user.getUserName(), userDto.getUserName())) {
                // 检查用户名是否已存在
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("user_name", userDto.getUserName());
                User existingUser = userMapper.selectOne(userQueryWrapper);
                if (existingUser != null) {
                    return false;
                }
            }
            // 更新用户信息
            user.setUserName(userDto.getUserName());
            user.setUserNickname(userDto.getUserNickname());
            user.setUserRealname(userDto.getUserRealname());
            user.setUserGender(userDto.getUserGender());
            user.setUserBirthday(userDto.getUserBirthday());
            user.setUpdateTime(java.time.LocalDateTime.now());
            user.setUserProfilePictureSrc(userDto.getUserProfilePictureSrc());
            
            // 执行更新操作
            int result = userMapper.updateById(user);
            return result > 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    @Override
    public Result<UserVo> getUserInfoById(Integer id) {
        // 检查用户ID是否为空
        if (id == null) {
            return Result.error(400, "用户ID不能为空");
        }

        // 根据ID查询用户信息
        User user = userMapper.selectById(id);
        
        // 如果用户不存在，返回错误信息
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        
        // 将User对象转换为UserVo对象
        UserVo userVo = new UserVo();
        userVo.setId(user.getId());
        userVo.setUserName(user.getUserName());
        userVo.setUserNickname(user.getUserNickname());
        userVo.setUserRealname(user.getUserRealname());
        userVo.setUserGender(user.getUserGender());
        userVo.setUserBirthday(user.getUserBirthday());
        userVo.setUserProfilePictureSrc(user.getUserProfilePictureSrc());
        userVo.setCreateTime(user.getCreateTime());
        userVo.setUpdateTime(user.getUpdateTime());
        
        // 返回成功结果
        return Result.success(userVo);
    }

    @Override
    public Result<Integer> removeUserById(Integer id) {
        if (id == null) {
            return Result.error(400, "用户ID不能为空");
        }
        boolean result = userMapper.deleteById(id) > 0;
        if (result) {
            return Result.success();
        }
        return Result.error(500, "删除用户失败");
    }
}